package sz;

import pojo.entity.Person;

import java.lang.reflect.*;

/**
 * 实战一：获取实体类的基本信息
 */
public class JavaBeanBasicInformation {
    public static void main(String[] args) {
        try {
            // 加载Person类
            Class<?> czl = Class.forName("pojo.entity.Person");

            // 获取类名
            String name = czl.getSimpleName();
            System.out.println("类名：" + name);

            // 获取修饰符
            int mod = czl.getModifiers();
            if ((mod & Modifier.PUBLIC) == Modifier.PUBLIC) {
                System.out.println("修饰符：public");
            } else if ((mod & Modifier.PRIVATE) == Modifier.PRIVATE) {
                System.out.println("修饰符：private");
            } else if ((mod & Modifier.PROTECTED) == Modifier.PROTECTED) {
                System.out.println("修饰符：protected");
            } else {
                System.out.println("修饰符：default(package)");
            }

            // 获取继承关系
            Class<?> superclass = czl.getSuperclass();
            if (superclass != null) {
                System.out.println("父类：" + superclass.getSimpleName());
            } else {
                System.out.println("父类：无");
            }

            // 获取无参构造方法
            Constructor<?> constructor = czl.getConstructor();
            Object instance = constructor.newInstance();
            System.out.println("无参构造方法创建的实例：" + instance);

            // 获取有参构造方法
            Constructor<?> parameterizedConstructor = czl.getConstructor(String.class);
            Object parameterizedInstance = parameterizedConstructor.newInstance("123");
            System.out.println("有参构造方法创建的实例：" + parameterizedInstance);

            // 获取类的属性
            Field[] fields = czl.getDeclaredFields();
            System.out.print("属性：");
            for (Field field : fields) {
                System.out.print(field.getName() + " ");
            }
            System.out.println();

            // 获取类的方法
            Method[] methods = czl.getDeclaredMethods();
            System.out.print("方法：");
            for (Method method : methods) {
                System.out.print(method.getName() + " ");
            }
            System.out.println();

        } catch (ClassNotFoundException e) {
            System.err.println("未找到类：pojo.entity.Person");
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            System.err.println("未找到指定的构造方法");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.err.println("构造方法调用异常");
            e.printStackTrace();
        } catch (InstantiationException e) {
            System.err.println("实例化异常");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.err.println("访问权限异常");
            e.printStackTrace();
        }
    }
}